package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.response.PageInfo;
import com.mars.framework.context.ContextUserInfoThreadHolder;
import com.mars.module.admin.entity.*;
import com.mars.module.admin.mapper.*;
import com.mars.module.admin.service.ISysDictDataService;
import com.mars.module.system.entity.SysUser;
import com.mars.module.system.mapper.SysUserMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.SysOrderRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.ISysOrderService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单业务层处理
 *
 * @author mars
 * @date 2024-04-15
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysOrderServiceImpl implements ISysOrderService {

    private final SysOrderMapper baseMapper;
    private final SysFoodMapper foodMapper;
    private final SysOrderDetailsMapper detailsMapper;
    private final SysShopCarMapper shopCarMapper;
    private final SysUserMapper userMapper;
    private final SysAddressMapper addressMapper;
    private final ISysDictDataService dataService;


    private String generateOrderNumber(String pre) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return pre + sdf.format(new Date());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysOrder add(SysOrderRequest request) {
        SysOrder entity = SysOrder.builder().build();
        BeanUtils.copyProperties(request, entity);
        entity.setSerialNo(generateOrderNumber("ORD"));
        entity.setStatus(0L);
        entity.setCreateTime(LocalDateTime.now());
        entity.setCreateById(ContextUserInfoThreadHolder.get().getId());
        baseMapper.insert(entity);
        List<SysShopCar> productList = request.getProductList();
        for (SysShopCar product : productList) {
            BigDecimal price = foodMapper.selectById(product.getFoodId()).getPrice();
            SysOrderDetails details = SysOrderDetails.builder().build();
            details.setOrderId(entity.getId());
            details.setAmount(product.getFoodNum());
            details.setProductId(product.getFoodId());
            details.setPrice(price.multiply(new BigDecimal(product.getFoodNum())));
            detailsMapper.insert(details);
            //删除购物车里的记录
            if ("1".equals(request.getIsShopCar())) {
                shopCarMapper.delete(new QueryWrapper<SysShopCar>().eq("user_id", product.getUserId()).eq("food_id", product.getFoodId()));
            }
        }
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(SysOrderRequest request) {
        SysOrder entity = SysOrder.builder().build();
        BeanUtils.copyProperties(request, entity);
        List<SysShopCar> productList = request.getProductList();
        if (productList != null && !productList.isEmpty()) {
            for (SysShopCar product : productList) {
                SysOrderDetails details = SysOrderDetails.builder().build();
                details.setOrderId(entity.getId());
                details.setAmount(product.getFoodNum());
                details.setProductId(product.getId());
                details.setPrice(product.getPrice().multiply(new BigDecimal(product.getFoodNum())));
                detailsMapper.updateById(details);
            }
        }
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public SysOrder getById(Long id) {
        List<SysOrderDetails> detailsList = detailsMapper.selectList(new QueryWrapper<SysOrderDetails>().eq("order_id", id));
        SysOrder order = baseMapper.selectById(id);
        if (detailsList != null && !detailsList.isEmpty()) {
            for (SysOrderDetails details : detailsList) {
                SysFood product = foodMapper.selectById(details.getProductId());
                details.setProductName(product.getName());
            }
        }
        SysAddress address = addressMapper.selectById(order.getAddressId());
        order.setAddressName(address == null ? "" : address.getName());
        order.setStatusName(dataService.getDictDataById("order_status", order.getStatus().toString()));
        SysUser sysUser = userMapper.selectById(order.getUserId());
        order.setUserName(sysUser == null ? "" : sysUser.getUserName());
        order.setProductList(detailsList);
        return order;
    }

    @Override
    public void updateStatus(String orderId, String status) {
        SysOrder order = baseMapper.selectById(orderId);
        order.setStatus(Long.parseLong(status));
        baseMapper.updateById(order);
    }

    @Override
    public PageInfo<SysOrder> pageList(SysOrderRequest request) {
        Page<SysOrder> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<SysOrder> query = this.buildWrapper(request);
        IPage<SysOrder> pageRecord = baseMapper.selectPage(page, query);
        List<SysOrder> records = pageRecord.getRecords();
        List<SysOrder> recordsNew = new ArrayList<>();
        for (SysOrder order : records) {
            SysUser sysUser = userMapper.selectById(order.getCreateById());
            order.setUserName(sysUser == null ? "" : sysUser.getUserName());
            SysAddress address = addressMapper.selectById(order.getAddressId());
            order.setAddressName(address.getName());
            order.setStatusName(dataService.getDictDataById("order_status", order.getStatus().toString()));
            recordsNew.add(order);
        }
        pageRecord.setRecords(recordsNew);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<SysOrder> list(SysOrderRequest request) {
        LambdaQueryWrapper<SysOrder> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    private LambdaQueryWrapper<SysOrder> buildWrapper(SysOrderRequest param) {
        LambdaQueryWrapper<SysOrder> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getSerialNo())) {
            query.like(SysOrder::getSerialNo, param.getSerialNo());
        }
        if (param.getTotalPrice() != null) {
            query.like(SysOrder::getTotalPrice, param.getTotalPrice());
        }
        if (param.getProductSum() != null) {
            query.eq(SysOrder::getProductSum, param.getProductSum());
        }
        if (StringUtils.isNotBlank(param.getHeatSum())) {
            query.like(SysOrder::getHeatSum, param.getHeatSum());
        }
        if (param.getStatus() != null) {
            query.eq(SysOrder::getStatus, param.getStatus());
        }
        return query;
    }

}
